package com.lyc.easyapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.lyc.easyapiclientsdk.utils.SignUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * 调用第三方接口的客户端
 *
 * @Author lyc
 * @Date 2023/6/13 21:16
 * @Version 1.0
 */
public class EasyApiClient {

    private static String GATEWAY_HOST = "http:/localhost:8090";

    public void setGATEWAY_HOST(String gateway_Host) {
        this.GATEWAY_HOST = gateway_Host;
    }

    private String accessKey;

    private String secretKey;

    public EasyApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

/*    //public String getNameByGet(String name){
    //    //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
    //    HashMap<String, Object> paramMap = new HashMap<>();
    //    paramMap.put("name", name);
    //
    //    String result = HttpUtil.get(GATEWAY_HOST + "/api/name/", paramMap);  // 对方提供的不是https服务的端口
    //    //System.out.println(result);
    //    return result;
    //}
    //
    //public String getNameByPost(String name){
    //    //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
    //    HashMap<String, Object> paramMap = new HashMap<>();
    //    paramMap.put("name", name);
    //
    //    String result = HttpUtil.post(GATEWAY_HOST + "/api/name/", paramMap);
    //    //System.out.println(result);
    //    return result;
    //}*/

    /**
     * 添加请求头信息
     * @param body
     * @return
     */
    private Map<String, String> getHeaderMap(String body) {
        if (body == null) {
            body = "zw";
        }
        String encode = null;
        //使用UTF-8编码对请求体内容进行URL编码
        try {
            encode = URLEncoder.encode(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        Map<String, String> hasMap = new HashMap<>();
        //防止重放，加nonce随机数，只能用一次，服务端要保存用过的随机数
        String nonce = RandomUtil.randomNumbers(4);
        String currentTime = String.valueOf(System.currentTimeMillis() / 1000);
        hasMap.put("accessKey", accessKey);
        //随机数，防止重放
        hasMap.put("nonce", nonce);
        //编码后的请求体
        hasMap.put("body", encode);
        //添加timestamp，检验时间戳是否过期
        hasMap.put("timestamp", currentTime);
        //流量染色，添加标识，
        hasMap.put("source", "gateway"); 
        //生成签名加密
        hasMap.put("sign", SignUtils.getSign(body, secretKey, nonce, currentTime));
        return hasMap;
    }

    public String onlineInvoke(String parameters, String url) {
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + url)
                .addHeaders(getHeaderMap(parameters))
                .body(parameters)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        return result;
    }
    
    public String onlineInvokeSelfByGet(String parameters, String url) throws Exception {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap = putParams(parameters);
        return HttpUtil.get(url, paramMap);
    }
    
    public String onlineInvokeSelfByPost(String parameters, String url) throws Exception {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap = putParams(parameters);
        return HttpUtil.post(url, paramMap);
    }
    
    // 将用户输入的参数通过算法分割开，放进hashMap中
    public HashMap<String, Object> putParams(String parameters) {
        HashMap<String, Object> paramMap = new HashMap<>();
        parameters = parameters.substring(1, parameters.length() - 1);
        String[] paramList = parameters.split(",");
        String first;
        String last;
        for (String s : paramList) {
            int i = s.indexOf(":");
            first = s.substring(1, i - 1);
            last = s.substring(i + 2, s.length() - 1);
            paramMap.put(first, last);
        }
        paramMap.put("format", "json");
        return paramMap;
    }
}
